#include <iostream>

#include "window.h"

#include <QtGui>
#include <QApplication>

#include <boost/thread.hpp>

#include <wells/v4lcameras.h>
#include <operators/motion.h>
#include <sinks/renderers.h>

int main(int argc, char *argv[])
{
   using namespace boost ;
   using namespace boost::posix_time ;

   using namespace crossEyed::wells ;
   using namespace crossEyed::operators ;
   using namespace crossEyed::sinks ;

   try {

      TV4L::TSpecificCamera camera("/dev/video0", 10);
      camera.prepare();
      camera.startStreaming();

      //intoQt::TRawRenderer renderer( &camera, QSize( 640, 480 ) ) ;
      //intoQt::TRawBlackAndWhiteRenderer renderer( &camera, QSize( 640, 480 ) ) ;

      //const crossEyed::core::TCountMonitor & processingMonitor = camera.getProcessingMonitor() ;

      //while( processingMonitor.getCounter() < 500 )
      //{
      //   this_thread::sleep(seconds(2));

      //   cout << processingMonitor.getCounter() << " frames in " << processingMonitor.getElapsedTime().total_milliseconds() << "ms.\n"
      //        << "Average framerate: " << processingMonitor.getAveragePerSecond() << " frames.\n" ;
      //}

      //this_thread::sleep(seconds(2));

      //TMotionFilter<TV4L::TFrame,TV4L::TToLuminancePixelAdapter> motionFilter( &camera,
      //                                                                         3, // number of output frames
      //                                                                         10, // number of temporary frames
      //                                                                         640, 480 );

      TAverageMotionFilter<TV4L::TFrame,TV4L::TToLuminancePixelAdapter> motionFilter( &camera,
                                                                                      3, // number of output frames
                                                                                      640, 480,
                                                                                      0.1 );
      intoQt::TByteFrameRenderer renderer( &motionFilter, QSize( 640, 480 ) ) ;


      QApplication a( argc, argv );
      Window w( &renderer );
      w.show();

      thread cameraThread( boost::ref(camera) ) ;
      thread motionFilterThread( boost::ref(motionFilter) ) ;
      thread rendererThread( boost::ref(renderer) ) ;

      a.exec();

      rendererThread.interrupt() ;
      rendererThread.join() ;

      motionFilterThread.interrupt() ;
      motionFilterThread.join() ;

      cameraThread.interrupt() ;
      cameraThread.join() ;

      camera.stopStreaming();
      camera.release();
   }
   catch(TException & e)
   {
      e.print(stderr);
   }
}
